﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IURIP;
using System.Xml;
using URIP.Tool;

namespace URIP.Core
{
    public class TargetRelationship : ITargetRelationship
    {
        public TargetRelationship(ITask task)
        {
            m_task = task;
        }

        private ITask m_task = null;
        private ITarget m_originalTarget = null;
        private ITarget m_relatedTarget = null;
        private IFilter m_condition = new Filter();
        private string m_listXPath = "";

        public ITask Task
        {
            get { return m_task; }
        }
        public ITarget RelatedTarget
        {
            get { return m_relatedTarget; }
        }
        public ITarget OriginalTarget
        {
            get { return m_originalTarget; }
        }
        public IFilter Condition
        {
            get { return m_condition; }
        }
        public string ListXPath
        {
            get { return m_listXPath; }
        }

        public void InitByConfiguration(XmlNode node)
        {
            string originalTargetName = Util.GetAttributeValue(node, "originalTarget");
            if (!m_task.Targets.ContainsKey(originalTargetName))
            {
                throw new Exception(string.Format("The target relationship must have valid originalTarget value."));
            }
            string relatedTargetName = Util.GetAttributeValue(node, "relatedTarget");
            if (!m_task.Targets.ContainsKey(relatedTargetName))
            {
                throw new Exception(string.Format("The target relationship must have valid relatedTarget value."));
            }
            m_originalTarget = m_task.Targets[originalTargetName];
            m_relatedTarget = m_task.Targets[relatedTargetName];
            this.m_listXPath = Util.GetAttributeValue(node, "listXPath");

            XmlNode filterNode = node.SelectSingleNode("./condition");
            if (filterNode != null)
            {
                m_condition.Name = Util.GetAttributeValue(filterNode, "name");
                if(m_condition.Name == "")
                {
                    throw new Exception(string.Format("The filter of target relationship must have valid name value."));
                }
                XmlNode queryNode = filterNode.SelectSingleNode("./query");
                if (queryNode != null)
                {
                    m_condition.Query = queryNode.InnerXml;
                }
            }
        }
    }
}
